package com.gzc.just.play.last.war.sceneserver.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;

import javax.sql.DataSource;

/**
 * 数据库连接池配置类
 * 
 * 配置HikariCP连接池参数，优化数据库连接性能
 * 作为Phase 4.3数据库持久化集成的一部分
 * 
 * 注意：此配置在dev-all-in-one模式下不加载，all-in-one使用SQLiteDataSourceConfig
 */
@Configuration
@Profile("!dev-all-in-one")
public class DatabasePoolConfig {
    
    @Value("${spring.datasource.url}")
    private String jdbcUrl;
    
    @Value("${spring.datasource.username}")
    private String username;
    
    @Value("${spring.datasource.password}")
    private String password;
    
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    
    @Value("${spring.datasource.hikari.connection-timeout:30000}")
    private long connectionTimeout;
    
    @Value("${spring.datasource.hikari.idle-timeout:600000}")
    private long idleTimeout;
    
    @Value("${spring.datasource.hikari.max-lifetime:1800000}")
    private long maxLifetime;
    
    @Value("${spring.datasource.hikari.maximum-pool-size:20}")
    private int maximumPoolSize;
    
    @Value("${spring.datasource.hikari.minimum-idle:10}")
    private int minimumIdle;
    
    @Value("${spring.datasource.hikari.pool-name:SceneServerHikariCP}")
    private String poolName;
    
    @Value("${lastwar.database.connection-pool-size:20}")
    private int customPoolSize;
    
    @Value("${lastwar.database.connection-timeout:30000}")
    private long customConnectionTimeout;
    
    @Value("${lastwar.database.idle-timeout:600000}")
    private long customIdleTimeout;
    
    /**
     * 配置HikariCP数据源
     * 
     * @return Hikari数据源
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(DataSource.class)
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    public DataSource dataSource() {
        HikariConfig config = new HikariConfig();
        
        // 基本连接配置
        config.setJdbcUrl(jdbcUrl);
        config.setUsername(username);
        config.setPassword(password);
        config.setDriverClassName(driverClassName);
        
        // 连接池配置
        config.setMaximumPoolSize(Math.max(maximumPoolSize, customPoolSize));
        config.setMinimumIdle(minimumIdle);
        config.setConnectionTimeout(Math.max(connectionTimeout, customConnectionTimeout));
        config.setIdleTimeout(Math.max(idleTimeout, customIdleTimeout));
        config.setMaxLifetime(maxLifetime);
        config.setPoolName(poolName);
        
        // 性能优化配置
        config.setAutoCommit(true);
        config.setConnectionTestQuery("SELECT 1");
        config.setValidationTimeout(3000);
        config.setLeakDetectionThreshold(60000); // 1分钟泄漏检测
        
        // 连接池初始化SQL
        config.setConnectionInitSql("SET NAMES utf8mb4");
        
        // 添加MySQL特定配置
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        config.addDataSourceProperty("useServerPrepStmts", "true");
        config.addDataSourceProperty("useLocalSessionState", "true");
        config.addDataSourceProperty("rewriteBatchedStatements", "true");
        config.addDataSourceProperty("cacheResultSetMetadata", "true");
        config.addDataSourceProperty("cacheServerConfiguration", "true");
        config.addDataSourceProperty("elideSetAutoCommits", "true");
        config.addDataSourceProperty("maintainTimeStats", "false");
        
        // 连接池状态监控
        config.setRegisterMbeans(true);
        
        return new HikariDataSource(config);
    }
    
    /**
     * 只读数据源配置
     * 用于报表查询等只读操作，可配置为从库连接
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.read-only.hikari")
    public DataSource readOnlyDataSource() {
        // 可以根据需要配置只读数据源，连接到从库
        // 目前复用主库配置
        return dataSource();
    }
}